package com.topisv.tms.utils.http;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.log.OrderLog;
//import com.topisv.tms.jms.SendMessageProducer;
import com.topisv.tms.jms.vo.SendMessage;
import com.topisv.tms.service.log.OrderLogService;

@Component
public class SynchOrdenoLog implements Runnable {

	@Autowired
	private OrderLogService orderLogService;
//	@Autowired
//	private SendMessageProducer sendMessageProducer;
	
	private static int pageSize=1000;
	
	private Object o=new Object();
	
	private volatile boolean flag=true;
	@Override
	public void run() {
		ObjectMapper objectMapper = new ObjectMapper();
		synchronized (o) {
			while(flag){
				Page<OrderLog> orderLogs=orderLogService.pageOrderLog(1, SynchOrdenoLog.pageSize);
				List<OrderLog> lists=orderLogs.getContent();
				if(lists.isEmpty()){
					try {
						o.wait(10000l);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						
					}
				}
				for(OrderLog l:lists){
					SendMessage send=new SendMessage();
					send.setType("WMSOrdenoLog");
					String json=null;
					try {
						json = objectMapper.writeValueAsString(l);
					} catch (JsonGenerationException e) {
						// TODO Auto-generated catch block
						
					} catch (JsonMappingException e) {
						// TODO Auto-generated catch block
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						
					}
					send.setMessage(json);
					//sendMessageProducer.sendTopic(send);
					l.setSynchStatus("finish");
					this.orderLogService.saveOrderLog(l);
				}
			}
		}
		

	}
	public void setFlag(boolean flag) {
		this.flag = flag;
	}

}
